package com.chat.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtil {

    // 生成秘钥
    private static final String SECRET = "my-very-strong-secret-key-1234567890";
    private static final SecretKey key = Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8));

    // Access Token 有效期：30 分钟
    private static final long ACCESS_EXPIRE = 30 * 60 * 1000;

    // Refresh Token 有效期：7 天
    private static final long REFRESH_EXPIRE = 7 * 24 * 60 * 60 * 1000;

    /**
     * 生成 Access Token
     */
    public static String generateAccessToken(Integer userId, String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject("ACCESS_TOKEN")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + ACCESS_EXPIRE))
                .signWith(key)
                .compact();
    }

    /**
     * 生成 Refresh Token
     */
    public static String generateRefreshToken(Integer userId, String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject("REFRESH_TOKEN")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + REFRESH_EXPIRE))
                .signWith(key)
                .compact();
    }

    /**
     * 解析 Token
     */
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .verifyWith(key) // 验签
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }

    /**
     * 判断 Token 是否过期
     */
    public static boolean isExpired(String token) {
        try {
            Claims claims = parseToken(token);
            Date exp = claims.getExpiration();
            log.info("解析成功, token过期时间: {}", exp);
            log.info("当前时间: {}", new Date());
            return exp.before(new Date());
        } catch (JwtException e) {
            log.error("token解析失败: {}", e.getMessage());
            return true; // 注意，这里返回的 true 可能不是过期，而是签名错误
        }
    }

}
